/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.yunhoo.cqq.announcement;

import com.yunhoo.cqq.document.FileUploadAnnounceBean;
import com.yunhoo.cqq.impl.IbatisAnnounce;


import com.yunhoo.cqq.model.Announcement;
import com.yunhoo.cqq.model.Document;
import com.yunhoo.cqq.model.PublicityData;
import com.yunhoo.cqq.util.FileUploadDownloadToolKit;
import com.yunhoo.cqq.util.StrUtil;
import com.yunhoo.sys.util.common.FacesUtils;
import com.yunhoo.sys.util.common.LoginParam;
import com.yunhoo.sys.util.common.NavigationTool;
import com.yunhoo.sys.util.common.ToolKit;
import com.yunhoo.sys.util.tree.MyTreeNodeImpl;
import com.yunhoo.sys.util.tree.TreeUtil;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import org.richfaces.component.UIDataTable;
import org.richfaces.event.TreeSelectionChangeEvent;
import org.richfaces.model.TreeNode;
import org.richfaces.model.TreeNodeImpl;

/**
 *
 * @author Administrator
 */
@ManagedBean(name = "announce")
@SessionScoped
public class AnnounceBean {

    private Announcement announce = new Announcement();//公告类
    private PublicityData type = new PublicityData();//公告类型
    private boolean imp = false;//公告重要性
    private List<Announcement> announcelist = new ArrayList<Announcement>();//table列表数据list
    private List<Announcement> selectlist = new ArrayList<Announcement>();//被选中判断中间list
    private UIDataTable data = null;
    private boolean all = false;//是否全选
    private boolean addOrUpdate = true;//判断是否是新增
    private List<Announcement> top3list = new ArrayList<Announcement>();//最新3条公告
    private Announcement topone = new Announcement();//最近一个公告对象
    private List<Announcement> top5list = new ArrayList<Announcement>();//最新5个公告
    private List<Announcement> leavinglist = new ArrayList<Announcement>();//更多公告
    private List<Document> doclist = new ArrayList<Document>();
    private int counter = 1;
    private TreeNode treenodes;

    public AnnounceBean() {
        announce = new Announcement();
        announce.setAuthor(LoginParam.getPer().getCpsn_number());
        announce.setCreatedate(new Date());
        announce.setLastchangedate(new Date());
        type = new PublicityData();
        announcelist = new ArrayList<Announcement>();
        selectlist = new ArrayList<Announcement>();
    }

    public TreeNode getTreenodes() {
        if (treenodes == null) {
            treenodes = new TreeNodeImpl();
            List typelist = IbatisAnnounce.getRootPublicityType();
            addNodes(typelist, treenodes);
        }

        return treenodes;
    }

    public void setTreenodes(TreeNode treenodes) {
        this.treenodes = treenodes;
    }

    private void addNodes(List typelist, TreeNode node) {
        for (int i = 0; i < typelist.size(); i++) {
            
            PublicityData item = (PublicityData) typelist.get(i);
            
            boolean isleaf = "1".equals(item.getIsEnd().trim()); //true : 是叶子节点
            
            TreeNodeImpl nodeImpl = new MyTreeNodeImpl(isleaf,item);
            
            node.addChild(item.getId(), nodeImpl);            
            
            item.setGradeLevel(item.getGradeLevel() + 1);
            
            if (!isleaf) {
                List typesublist = IbatisAnnounce.getSubPublicityType(item);
                addNodes(typesublist, nodeImpl);
            }
        }
    }

    public void editor() {
//        System.out.println(announce.getType());
        if (announce.getType() == null) {
            ToolKit.msgs_info(FacesContext.getCurrentInstance(), null, "请先选择类别");
        } else {
            NavigationTool.getSelectedUrl("/page/announcement/fckeditor.xhtml");
        }
    }

    public void publish() {
        System.out.println("-------in++++++++++++");
        FileUploadAnnounceBean fileUpload = (FileUploadAnnounceBean) FacesUtils.getManagedBean("fileUploadAnnounceBean");
        if (addOrUpdate) {
            announce.setAuthor(LoginParam.getPer().getCpsn_number());
            announce.setCreatedate(new Date());
            announce.setLastchangedate(new Date());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String str = sdf.format(announce.getCreatedate());
            int id = (int) ((Integer) 100000 * Math.random());
            announce.setId(str + announce.getType() + id);
            announce.setAuditflag("0");
            announce.setDocid(fileUpload.getId());
            announce.setUrl(fileUpload.getMyurl());
            if (imp) {
                announce.setImportance("1");
            } else {
                announce.setImportance("0");
            }
            IbatisAnnounce.insertAnnounce(announce);
        } else {
            if (imp) {
                announce.setImportance("1");
            } else {
                announce.setImportance("0");
            }
            if (StrUtil.isEmpty(fileUpload.getMyurl())) {
                announce.setUrl(fileUpload.getMyurl());
            }

            announce.setLastchangedate(new Date());
            IbatisAnnounce.updateAnnounce(announce);
        }
        announce = new Announcement();
        
        initAnnoounceList(type.getId());
        NavigationTool.getSelectedUrl("/page/announcement/announcelist.xhtml");
    }

    public void queryTitle() {
        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        String id = request.getParameter("qtitle");
        announce = new Announcement();
        announce = (Announcement) IbatisAnnounce.getAnnounceById(id);    
        File file = new File(announce.getUrl());
        if (file.exists()) {
            announce.setShowflag(true);
        } else {
            announce.setShowflag(false);
        }


        if (announce.getUrl() != null) {
            String name = StrUtil.getShortPathWin(announce.getUrl());
            announce.setDocname(name);

//            String str;
//            try {
//                str = new String(announce.getUrl().getBytes("utf-8"), "iso-8859-1");
//                announce.setUrl(str);
//            } catch (UnsupportedEncodingException ex) {
//                Logger.getLogger(AnnounceBean.class.getName()).log(Level.SEVERE, null, ex);
//            }
        }
        NavigationTool.getSelectedUrl("/page/announcement/readannounce.xhtml");
    }

    public void qid() {
        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        String id = request.getParameter("qid");
        announce = (Announcement) IbatisAnnounce.getAnnounceById(id);
        NavigationTool.getSelectedUrl("/page/announcement/readannounce.xhtml");
    }

    public void qmore() {
        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        String id = request.getParameter("qmore");
        announce = new Announcement();
        announce = (Announcement) IbatisAnnounce.getAnnounceById(id);
//        String str;
//        try {
//            str = new String(announce.getUrl().getBytes("utf-8"), "iso-8859-1");
//            announce.setUrl(str);
//        } catch (UnsupportedEncodingException ex) {
//            Logger.getLogger(AnnounceBean.class.getName()).log(Level.SEVERE, null, ex);
//        }

        NavigationTool.getSelectedUrl("/page/announcement/readannounce.xhtml");
    }

    public void readback() {
        NavigationTool.getSelectedUrl("/page/announcement/foreground.xhtml");
    }

    public void preview() {
        NavigationTool.getSelectedUrl("/page/announcement/preview.xhtml");
    }

    public void back() {
        NavigationTool.getSelectedUrl("/page/announcement/fckeditor.xhtml");
    }

    public void goback() {
        NavigationTool.getSelectedUrl("/page/announcement/foreground.xhtml");
    }

    public void reselect() {
        NavigationTool.getSelectedUrl("/page/announcement/choicetype.xhtml");
    }

    public void selected(TreeSelectionChangeEvent event) {//编辑-公告类型侦听
        type = (PublicityData) TreeUtil.listener(event);
        announce.setType(type.getId());
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void selected2(TreeSelectionChangeEvent event) {//查看-公告类型侦听
        type = (PublicityData) TreeUtil.listener(event);
        String id = type.getId();
        announcelist = new ArrayList<Announcement>();
        initAnnoounceList(id);
//        doclist=IbatisDocument.get

    }
    
    private void initAnnoounceList(String typeId){
        announcelist = IbatisAnnounce.getSelectAnnounce(typeId);
        if (announcelist != null && announcelist.size() > 0) {
            for (Announcement ac : announcelist) {
                if (ac.getDocid() != 0) {
                    String ss = "";
//                    try {
//                        ss = new String(ac.getUrl().getBytes("utf-8"), "iso-8859-1");
//                        System.out.println("file:" + ac.getUrl());
//                    } catch (UnsupportedEncodingException ex) {
//                        Logger.getLogger(AnnounceBean.class.getName()).log(Level.SEVERE, null, ex);
//                    }
                    if (ac.getUrl() != null) {
                        String name = StrUtil.getShortPathWin(ac.getUrl().trim());
                        //ac.setUrl(ss);
                        ac.setDocname(name);
                        System.out.println("doc:" + ac.getDocname());
                    }
                }
            }
        }
    }

    public void showContent(Announcement row) {  //查看公告具体内容
        announce = row;
        NavigationTool.getSelectedUrl("/page/announcement/showcontent.xhtml");
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void backtolist() {
        NavigationTool.getSelectedUrl("/page/announcement/announcelist.xhtml");
    }

    public void isselect() {
        selectlist = announcelist;
        announcelist = new ArrayList<Announcement>();
        if (selectlist != null && selectlist.size() > 0) {
            for (int i = 0; i < selectlist.size(); i++) {
                Announcement announce = selectlist.get(i);
                announce.setCheck(all);
                announcelist.add(announce);
            }
        }

//        System.out.println("i am in isselec " + announcelist.size());
    }

    public void add() {
        addOrUpdate = true;
        announce = new Announcement();
        NavigationTool.getSelectedUrl("/page/announcement/choicetype.xhtml");
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void update() {
//        if (announce.getAuditflag().equals("1")) {
//            ToolKit.msgs_info(FacesContext.getCurrentInstance(), null, "请先销审再修改");
//        } else {
            addOrUpdate = false;
            FacesUtils.setSessionAttribute("fileUploadAnnounceBean", new FileUploadAnnounceBean());
            if (announce != null && announce.getImportance().equals("1")) {
                imp = true;
            }
            NavigationTool.getSelectedUrl("/page/announcement/fckeditorUpdate.xhtml");
            FacesContext.getCurrentInstance().renderResponse();
        //}
    }

    public void delete() {
        if (announcelist != null && announcelist.size() > 0) {
            for (Announcement ac : announcelist) {
                if (ac.isCheck()) {
//                    if (ac.getAuditflag().equals("1")) {
//                        ToolKit.msgs_info(FacesContext.getCurrentInstance(), null, "未销审不能删除");
//                    } else {
                        IbatisAnnounce.deleteSelectAnnounce(ac);
               //     }
                }
            }
        }
        announcelist = IbatisAnnounce.getSelectAnnounce(type.getId());
    }

    public void auditflag() {
        if (announcelist != null && announcelist.size() > 0) {
            for (Announcement ac : announcelist) {
                if (ac.isCheck()) {
                    ac.setAuditor(LoginParam.getPer().getCpsn_number());
                    ac.setAuditflag("1");
                    ac.setAuditdate(new Date());
                    IbatisAnnounce.updateSelectAudit(ac);
                }
            }
        }
    }

    public void cancelAuditflag() {
        if (announcelist != null && announcelist.size() > 0) {
            for (Announcement ac : announcelist) {
                if (ac.isCheck()) {
                    ac.setAuditflag("0");
                    ac.setAuditor("");
                    IbatisAnnounce.cancelSelectAudit(ac);
                }
            }
        }
    }

    public void getmore() {
        leavinglist = IbatisAnnounce.getLeavingAnnounce();
        NavigationTool.getSelectedUrl("/page/announcement/getmore.xhtml");
    }

    public void read(){        
        FileUploadDownloadToolKit.download(topone.getUrl());
    }

    public void attatch(){
        FileUploadDownloadToolKit.download(announce.getUrl());
    }
    //下载附件
    public void download(Announcement row){
        Announcement  doc = row;
        String fileName = doc.getUrl();
        System.out.println("file:" + fileName);
        FileUploadDownloadToolKit.download(fileName);
    }

    public Announcement getAnnounce() {
        return announce;
    }

    public void setAnnounce(Announcement announce) {
        this.announce = announce;
    }

    public boolean isImp() {
        return imp;
    }

    public void setImp(boolean imp) {
        this.imp = imp;
    }

    public PublicityData getType() {
        return type;
    }

    public void setType(PublicityData type) {
        this.type = type;
    }

    public List<Announcement> getAnnouncelist() {
        if (announcelist == null) {
            announcelist = new ArrayList<Announcement>();
        }
        return announcelist;
    }

    public void setAnnouncelist(List<Announcement> announcelist) {
        this.announcelist = announcelist;
    }

    public List<Announcement> getSelectlist() {
        return selectlist;
    }

    public void setSelectlist(List<Announcement> selectlist) {
        this.selectlist = selectlist;
    }

    public UIDataTable getData() {
        return data;
    }

    public void setData(UIDataTable data) {
        this.data = data;
    }

    public boolean isAll() {
        return all;
    }

    public void setAll(boolean all) {
        this.all = all;
    }

    public boolean isAddOrUpdate() {
        return addOrUpdate;
    }

    public void setAddOrUpdate(boolean addOrUpdate) {
        this.addOrUpdate = addOrUpdate;
    }

    public List<Announcement> getTop3list() {
        top3list = IbatisAnnounce.getTop3Announce();
        return top3list;
    }

    public void setTop3list(List<Announcement> top3list) {
        this.top3list = top3list;
    }

    public Announcement getTopone() {
        topone = (Announcement) IbatisAnnounce.getTop1Announce();
        if (topone != null && topone.getUrl() != null) {
            if (topone.getUrl() != null) {
                String name = StrUtil.getShortPathWin(topone.getUrl());
                topone.setDocname(name);
            }

            File file = new File(topone.getUrl());
            if (file.exists()) {
                topone.setShowflag(true);
            } else {
                topone.setShowflag(false);
            }
//            if (topone != null && topone.getUrl() != null) {
//                String str;
//                try {
//                    //str = new String(topone.getUrl().getBytes("utf-8"), "iso-8859-1");
//                    topone.setUrl(topone.getUrl());
//                } catch (UnsupportedEncodingException ex) {
//                    Logger.getLogger(AnnounceBean.class.getName()).log(Level.SEVERE, null, ex);
//                }
//            }
        }
        return topone;
    }

    public void setTopone(Announcement topone) {
        this.topone = topone;
    }

    public List<Announcement> getLeavinglist() {

        return leavinglist;
    }

    public void setLeavinglist(List<Announcement> leavinglist) {
        this.leavinglist = leavinglist;
    }
    
    public List<Announcement> getTop5list() {
        top5list = IbatisAnnounce.getTop5Announce();
        return top5list;
    }

    public void setTop5list(List<Announcement> top5list) {
        this.top5list = top5list;
    }

    public List<Document> getDoclist() {
        return doclist;
    }

    public void setDoclist(List<Document> doclist) {
        this.doclist = doclist;
    }
}
